import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import {ActivatedRoute, Router} from "@angular/router";
import {ApiService} from "../../environments/environment";


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  validateForm: FormGroup;


  constructor(private fb: FormBuilder ,
              private router: Router,
              private api:ApiService) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required ] ],
      remember: [ true ]
    });
    if(sessionStorage.getItem('remember') === 'true'  ) {
      this.validateForm.patchValue({
        userName:sessionStorage.getItem('userName'),
        password:sessionStorage.getItem('password')
      })
    }
  }

  login(): void {

    this.api.login.login({...this.validateForm.value}).then(data => {
      if(data){
          if(this.validateForm.value.remember){
            sessionStorage.setItem('remember','true')
            sessionStorage.setItem('userName',this.validateForm.value.userName)
            sessionStorage.setItem('password',this.validateForm.value.password)
          }else {
            sessionStorage.removeItem('remember')
            sessionStorage.removeItem('userName')
            sessionStorage.removeItem('password')
          }
          this.router.navigateByUrl('/home');
        }
    })

  }
}
